<?php
class PdoDbEngine
{
    private $_conn;
    
    public function __construct()
    {
    }
    
    public function connect($db_conf)
    {
        switch($db_conf['db_product']) {
        case 'mysql' :
            $dsn = 'mysql:';
            if (!empty($db_conf['unix_domain_socket'])) {
                $dsn .= 'unix_socket=' . $db_conf['unix_domain_socket'] . ';';
            } else {
                $dsn .= 'host=' . $db_conf['host'] . ';';
            }
            $dsn .= 'dbname=' . $db_conf['db_name'];
            $this->_conn = new PDO($dsn, $db_conf['username'], $db_conf['password']);
            break;
        case 'pgsql' :
            $dsn = 'pgsql:host=' . $db_conf['host'] . ';port=' . $db_conf['port']
            . ';dbname=' . $db_conf['db_name'] . ';user=' . $db_conf['username']
            . ';password=' . $db_conf['password'];
            $this->_conn = new PDO($dsn);
            break;
        }
        //http://php.net/manual/en/pdo.setattribute.php
        $this->_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        return $this->_conn;
    }

    public function delete($sql)
    {
        return $this->_conn->exec($sql); //todo delete 是幂等的？
    }
    
    public function insertRow($sql)
    {
        $this->_conn->exec($sql);
        return $this->_conn->lastInsertId(); //todo
    }
    
    public function insertRows($sql)
    {
        return $this->_conn->exec($sql);
    }

    public function query($sql)
    {
        $r = $this->_conn->query($sql);
        if (empty($r)) {
            return array();
        }
        $r->setFetchMode(PDO::FETCH_ASSOC);
        return $r->fetchAll();
    }

    public function selectCount($sql)
    {
        $r = $this->_conn->query($sql);
        return intval($r->fetchColumn());
    }
    
    public function selectRow($sql)
    {
        $r = $this->selectRows($sql);
        return empty($r) ? array() : $r[0];
    }
    
    public function selectRows($sql)
    {
        $r = $this->_conn->query($sql);
        $r->setFetchMode(PDO::FETCH_ASSOC);
        return $r->fetchAll();
    }
    
    public function update($sql)
    {
        return $this->_conn->exec($sql);
    }
}
?>
